import easygui as eg
from database import Database


def show_route_management(db, current_user):
    while True:
        # 获取线路列表
        routes = db.execute_query("""
            SELECT RouteID, RouteName, Destination, Days, Price, 
                   CASE WHEN Status = 1 THEN '启用' ELSE '禁用' END AS StatusText
            FROM TravelRoutes
            ORDER BY RouteName
        """)

        if not routes:
            eg.msgbox("没有线路数据", "线路管理")
            break

        # 格式化显示
        route_list = [
            f"ID:{r['RouteID']} | 线路名:{r['RouteName']} | 目的地:{r['Destination']} | "
            f"天数:{r['Days']}天 | 价格:{r['Price']}元 | 状态:{r['StatusText']}"
            for r in routes
        ]

        # 添加操作选项
        route_list.extend(["", "=== 操作选项 ===", "1. 添加线路", "2. 查看详情", "3. 编辑线路", "4. 返回"])

        choice = eg.choicebox("旅游线路管理系统", "线路管理", route_list)

        if not choice or choice == "4. 返回":
            break

        if choice == "1. 添加线路":
            add_route(db)
        elif choice == "2. 查看详情":
            route_id = get_id_from_choice(choice)
            if route_id:
                view_route_details(db, route_id)
        elif choice == "3. 编辑线路":
            route_id = get_id_from_choice(choice)
            if route_id:
                edit_route(db, route_id)


def get_id_from_choice(choice):
    if "ID:" not in choice:
        return None
    return int(choice.split("ID:")[1].split("|")[0].strip())


def add_route(db):
    fields = [
        "线路名称*", "目的地*", "天数*", "价格*",
        "特色介绍", "行程安排", "注意事项", "状态(1启用/0禁用)"
    ]
    values = eg.multenterbox("添加新线路", "线路管理", fields)

    if not values:
        return

    # 验证必填字段
    if not all(values[:4]):
        eg.msgbox("带*的字段为必填项", "错误")
        return

    try:
        db.execute_query("""
            INSERT INTO TravelRoutes (
                RouteName, Destination, Days, Price, 
                Features, Itinerary, Notice, Status
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        """, (*values[:4], values[4] or None, values[5] or None, values[6] or None, int(values[7])), False)

        eg.msgbox("线路添加成功", "成功")
    except Exception as e:
        eg.msgbox(f"添加失败: {str(e)}", "错误")


def view_route_details(db, route_id):
    route = db.execute_query("""
        SELECT * FROM TravelRoutes WHERE RouteID = ?
    """, (route_id,))[0]

    # 获取相关旅游团
    groups = db.execute_query("""
        SELECT GroupID, GroupName, StartDate, EndDate, Status
        FROM TravelGroups
        WHERE RouteID = ?
        ORDER BY StartDate
    """, (route_id,))

    # 构建显示信息
    info = f"=== 基本信息 ===\n"
    info += f"线路名称: {route['RouteName']}\n"
    info += f"目的地: {route['Destination']}\n"
    info += f"天数: {route['Days']}天\n"
    info += f"价格: {route['Price']}元\n"
    info += f"状态: {'启用' if route['Status'] else '禁用'}\n\n"
    info += f"=== 特色介绍 ===\n{route['Features'] or '无'}\n\n"
    info += f"=== 行程安排 ===\n{route['Itinerary'] or '无'}\n\n"
    info += f"=== 注意事项 ===\n{route['Notice'] or '无'}\n\n"

    if groups:
        info += "=== 相关旅游团 ===\n"
        for g in groups:
            info += (
                f"团ID: {g['GroupID']} | 团名: {g['GroupName']} | "
                f"时间: {g['StartDate'].strftime('%Y-%m-%d')}到{g['EndDate'].strftime('%Y-%m-%d')} | "
                f"状态: {get_group_status(g['Status'])}\n"
            )
    else:
        info += "=== 暂无相关旅游团 ===\n"

    eg.textbox("线路详细信息", "线路详情", info)


def get_group_status(status):
    status_map = {
        'pending': '待确认',
        'confirmed': '已确认',
        'completed': '已完成',
        'cancelled': '已取消'
    }
    return status_map.get(status, status)


def edit_route(db, route_id):
    route = db.execute_query("""
        SELECT * FROM TravelRoutes WHERE RouteID = ?
    """, (route_id,))[0]

    fields = [
        "线路名称*", "目的地*", "天数*", "价格*",
        "特色介绍", "行程安排", "注意事项", "状态(1启用/0禁用)"
    ]
    values = [
        route['RouteName'],
        route['Destination'],
        str(route['Days']),
        str(route['Price']),
        route['Features'] or "",
        route['Itinerary'] or "",
        route['Notice'] or "",
        str(route['Status'])
    ]

    new_values = eg.multenterbox("编辑线路信息", "线路编辑", fields, values)

    if not new_values:
        return

    # 验证必填字段
    if not all(new_values[:4]):
        eg.msgbox("带*的字段为必填项", "错误")
        return

    try:
        db.execute_query("""
            UPDATE TravelRoutes SET 
                RouteName = ?, Destination = ?, Days = ?, Price = ?,
                Features = ?, Itinerary = ?, Notice = ?, Status = ?
            WHERE RouteID = ?
        """, (*new_values[:4],
              new_values[4] or None, new_values[5] or None, new_values[6] or None,
              int(new_values[7]), route_id), False)

        eg.msgbox("线路更新成功", "成功")
    except Exception as e:
        eg.msgbox(f"更新失败: {str(e)}", "错误")